"""
员工增删改查的业务
"""

from fastapi import APIRouter, HTTPException
from fastapi.params import Query

from apps.employee.models import Employee, Dept
from apps.employee.schemas import EmployeeInt

empRouter = APIRouter()

# 查询所有员工信息 支持模糊查询
@empRouter.get('/')
async def get_Employees(
        page:int = Query(1,ge=1,description="页码"),
        empName:str = Query(None,description="用户名"),
):
    # 计算偏移量（每一页从第几条数据开始）
    # 如果每页10条
    # 第一页  0  9
    # 第二页  10 19
    # 第三页  20 29
    page_size = 10
    start = (page - 1) * page_size
    # 获取总数据条数
    total = await Employee.all().count()
    # 获取分页数据
    data = await Employee.all()

    if empName:
        data = await Employee.filter(name=empName).offset(start).limit(page_size)
    else:
        data = await Employee.all().offset(start).limit(page_size)
    # 计算总页数
    total_pages = (total + page_size - 1) // page_size

    # 处理返回数据，包含部门名称
    result_data = []
    for emp in data:
        dept = await Dept.get(id=emp.dept_id)
        emp_dict = {
            'id': emp.id,
            'name': emp.name,
            'age': emp.age,
            'email': emp.email,
            'dept_id': emp.dept_id,
            'dept_name': dept.name, # 添加部门名称
            'created': emp.created,

        }
        result_data.append(emp_dict)



    return {
        'total': total,
        'page':page,
        'total_pages':total_pages,
        'data': result_data,
        'page_size':page_size
    }




# 根据Id查询员工信息
@empRouter.get('/{empId}')
async def get_Employee(empId: int):
    employee = await Employee.get(id=empId)
    # 根据employee的Id查询出部门
    dept = await Dept.get(id=employee.dept_id)
    dept_list = await Dept.all()

    # for dept in dept_list:
    #     print(dept)
    return {
        'employee': employee,
        'dept': dept,
        'dept_list':dept_list,
    }



# 修改员工信息
@empRouter.put('/{empId}')
async def update_Employee(empId:int,employee:EmployeeInt):
    # 处理一对多的关系
    data = employee.model_dump()
    dept = data.pop('dept_id')

    # 修改员工信息
    await Employee.filter(id=empId).update(**data)
    return {
        'status_code': 200,
        'detail': 'Employee updated'
    }

# 删除员工信息
@empRouter.delete('/{empId}')
async def delete_Employee(empId:int):
    rows = await Employee.filter(id=empId).delete()
    if rows == 0:
        raise HTTPException(status_code=404, detail="Employee not found")
    else:
        return {
            'status_code':200,
            'detail':'Employee deleted'
        }

# 增加员工信息
@empRouter.post('/employee')
async def add_Employee(employee:EmployeeInt):
    # 检查邮箱是否存在
    exiting_email = await Employee.filter(email = employee.email).first()
    print(exiting_email)
    if exiting_email:
        raise HTTPException(status_code=409, detail="Email already exists")


    # 因为model中是dept,数据库中是dept_id 所以需要解决一对多的问题
    data = employee.model_dump(exclude={'dept_id'})
    dept = await Dept.get(id=employee.dept_id)

    await Employee.create(**data,dept=dept)
    dept_list = await Dept.all()


    return {
        'status_code':200,
        'detail':'Employee created',
        'dept_list': dept_list,
    }